from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import os
import platform


def login_and_get_title(username: str, password: str):
    """
    自动化登录携程，支持人工输入短信验证码，登录后跳转目标页面并获取标题。
    """
    from selenium.common.exceptions import TimeoutException
    import json
    chrome_options = Options()
    # chrome_options.add_argument('--headless')  # 登录流程建议可视化
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--window-size=1920,1080')
    url = "https://hotels.ctrip.com/hotels/listPage?cityename=hangzhou&city=17&optionId=17&optionType=City&checkin=2025/07/08&checkout=2025/07/09"
    driver = None
    try:
        # 清理可能损坏的ChromeDriver缓存
        try:
            chromedriver_path = ChromeDriverManager().install()
            print(f"ChromeDriverManager返回路径: {chromedriver_path}")
            
            # 修复路径问题：ChromeDriverManager有时返回错误的文件
            if platform.system() == "Windows":
                # 查找正确的chromedriver.exe文件
                driver_dir = os.path.dirname(chromedriver_path)
                possible_paths = [
                    os.path.join(driver_dir, "chromedriver.exe"),
                    os.path.join(driver_dir, "chromedriver-win32", "chromedriver.exe"),
                    os.path.join(os.path.dirname(driver_dir), "chromedriver.exe"),
                    chromedriver_path if chromedriver_path.endswith(".exe") else None
                ]
                
                actual_driver_path = None
                for path in possible_paths:
                    if path and os.path.exists(path) and path.endswith(".exe"):
                        file_size = os.path.getsize(path)
                        if file_size > 1000:  # 确保文件不是空的或损坏的
                            actual_driver_path = path
                            print(f"找到有效的ChromeDriver: {actual_driver_path} (大小: {file_size} bytes)")
                            break
                
                if not actual_driver_path:
                    raise Exception("未找到有效的chromedriver.exe文件")
                
                chromedriver_path = actual_driver_path
            
            # 检查文件是否存在且可执行
            if not os.path.exists(chromedriver_path):
                raise Exception("ChromeDriver文件不存在")
            
            service = Service(chromedriver_path)
            print(f"使用ChromeDriver: {chromedriver_path}")
            
        except Exception as driver_error:
            print(f"ChromeDriver安装/检查失败: {driver_error}")
            print("尝试使用系统PATH中的chromedriver...")
            service = Service()  # 使用系统PATH中的chromedriver
        
        driver = webdriver.Chrome(service=service, options=chrome_options)
        driver.get(url)
        print("正在访问目标页面，若未登录会自动跳转到登录页...")
        # 等待账号输入框出现
        # WebDriverWait(driver, 120).until(
        #     EC.presence_of_element_located((By.CSS_SELECTOR, "input[data-testid='accountNameInput']"))
        # )
        # 输入账号
        driver.find_element(By.CSS_SELECTOR, "input[data-testid='accountNameInput']").send_keys(username)
        # 输入密码
        driver.find_element(By.CSS_SELECTOR, "input[data-testid='passwordInput']").send_keys(password)
        # 点击登录按钮
        driver.find_element(By.CSS_SELECTOR, "input[data-testid='loginButton']").click()
        print("已提交账号密码，请在弹出的页面手动输入短信验证码并完成验证...")
        # 等待用户完成短信验证码验证（可根据页面跳转判断）
        WebDriverWait(driver, 120).until(
            lambda d: url in d.current_url or "passport.ctrip.com" not in d.current_url
        )
        print("登录成功，正在跳转目标页面...")
        driver.get(url)
        time.sleep(3)
        title = driver.title
        print(f"页面标题: {title}")
        # 保存cookie，便于后续复用
        cookies = driver.get_cookies()
        with open("cookies.json", "w", encoding="utf-8") as f:
            json.dump(cookies, f)
        print("登录cookie已保存，可用于后续免登录访问。")
        return title
    except TimeoutException:
        print("等待超时，可能未完成短信验证或页面未跳转。")
        return None
    except Exception as e:
        print(f"发生错误: {str(e)}")
        return None
    finally:
        if driver:
            driver.quit()
            print("浏览器已关闭")


# # 用法示例：
if __name__ == '__main__':
    # 请替换为你的携程账号和密码
    login_and_get_title("你的账号", "你的密码")